package xml.resource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.dbutils.DbUtils;
import org.jdom.JDOMException;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import xml.form.Form;
import xml.model.User;
import xml.validator.LengthValidator;
import xml.validator.NotEmptyValidator;

/**
 * Resource qui permet l'authentification des utilisateurs ayant accès au service
 * Méthodes: POST
 * @author marya
 */
public class AuthentificationResource extends AbstractResource {

    public AuthentificationResource() {
        super();
    }

    @Post
    public Representation doPost(Representation entity) throws IOException, JDOMException {
        Representation response = null;
        Connection connexion = null;
        final String sqlUser = "SELECT id_user, nom, prenom FROM USER WHERE login = ? AND password = ?";

        Form form = getAuthentificationForm(entity);
        if (!form.isValid()) {
            for (String error : form.getMessages()) {
                errors.add(new ResourceError(error));
                setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            }
        } else {
            try {
                connexion = database.getNewConnection();
                PreparedStatement ps = connexion.prepareStatement(sqlUser);
                ps.setString(1, form.getFirstValue("login"));
                ps.setString(2, form.getFirstValue("password"));
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    User user = new User(rs.getInt("id_user"), rs.getString("nom"), rs.getString("prenom"));
                    response = user.toXML();
                } else {
                    setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                }
                rs.close();
                ps.close();
                connexion.close();
            } catch (SQLException ex) {
                Logger.getLogger(AuthentificationResource.class.getName()).log(Level.SEVERE, null, ex);
                DbUtils.closeQuietly(connexion);
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, ex);
            }
        }
        if (!errors.isEmpty()) {
            response = ResourceError.getListRepresentation(errors);
        }
        return response;
    }

    public Form getAuthentificationForm(Representation entity) {
        Form form = new Form(entity);
        NotEmptyValidator notEmptyValidator = new NotEmptyValidator();
        LengthValidator lengthValidator = new LengthValidator(255);

        form.addValidators("login", notEmptyValidator, lengthValidator);
        form.addValidators("password", notEmptyValidator, lengthValidator);

        return form;

    }
}
